package com.sanjiahantang.youjiarole.module.common.views.impl;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.popuwindow.SelectPhotoPopupwindow;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.uilibrary.views.CircleImageView;
import com.sanjiahantang.uilibrary.views.GridViewFixScroll;
import com.sanjiahantang.uilibrary.views.ObservableScrollView;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseMvpFragment;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.module.common.beans.MeIcon;
import com.sanjiahantang.youjiarole.module.common.presenters.MePresenter;
import com.sanjiahantang.youjiarole.module.common.views.MeView;
import com.sanjiahantang.youjiarole.module.login.beans.LoginBean;
import com.sanjiahantang.youjiarole.module.login.views.impl.LoginActivity;
import com.sanjiahantang.youjiarole.module.me.order.views.OrderView;
import com.sanjiahantang.youjiarole.utils.CheckUtil;
import com.sanjiahantang.youjiarole.utils.FileUtils;
import com.sanjiahantang.youjiarole.utils.SPUtils;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import q.rorbin.badgeview.QBadgeView;

import static com.sanjiahantang.uilibrary.utils.Utils.checkIsVisible;
import static com.sanjiahantang.uilibrary.utils.Utils.isNetworkAvailable;


/**
 * 个人中心
 */
public class MeFragment extends BaseMvpFragment<MeView, MePresenter> implements MeView, View.OnClickListener, AdapterView.OnItemClickListener, ObservableScrollView.OnScrollChangedListener {


    private CircleImageView headPhoto;
    private View lineLay_not_login, mainTitle, titleView,txtQR;
    private RelativeLayout lineLay_login;
    private RelativeLayout rl_CSD;
    private RelativeLayout rl_evaluate;
    private RelativeLayout rlCustomer;
    private RelativeLayout rl_lineSettings;//设置键
    private LinearLayout ll_detail;
    private TextView txtNickname,txtRole;
    private GridViewFixScroll gridView;
    private QBadgeView messageQbv,titleMessageQbv;
    private View mView,panelDetail;
    private ObservableScrollView scrollView;
    private SelectPhotoPopupwindow photoPopupwindow;
    private RelativeLayout rlPartner;
    private RelativeLayout meAccount;
    private TextView tv_city, tv_qytime, tv_pf;
    private int[] orderTypes = new int[]{
            OrderView.TYPE_UN_PAY,
            OrderView.TYPE_PART_PAY,
            OrderView.TYPE_PAYED,
            OrderView.TYPE_COMPLETE,

    };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mView != null) {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null) {
                parent.removeView(mView);
            }
        } else {
            mView = inflater.inflate(R.layout.fragment_me, container, false);
        }
        return mView;
    }


    @Override
    protected void initView() {
        mView.findViewById(R.id.titleView).setVisibility(View.GONE);
        gridView = (GridViewFixScroll) mView.findViewById(R.id.gridview);

        lineLay_not_login = mView.findViewById(R.id.lineLay_not_login);
        txtQR = mView.findViewById(R.id.txtQR);
        lineLay_login = (RelativeLayout) mView.findViewById(R.id.lineLay_login);
        mainTitle = mView.findViewById(R.id.mainTitle);
        titleView = mView.findViewById(R.id.titleView);
//        rl_leavemsg= (RelativeLayout) mView.findViewById(R.id.layout_message);

        rl_evaluate = (RelativeLayout) mView.findViewById(R.id.layout_evaluate);
        ll_detail = (LinearLayout) mView.findViewById(R.id.ll_my_detail);
        rl_lineSettings = (RelativeLayout) mView.findViewById(R.id.lineSettings);
        headPhoto = (CircleImageView) mView.findViewById(R.id.imgHead);
        txtNickname = (TextView) mView.findViewById(R.id.txtNickname);
        txtRole = (TextView) mView.findViewById(R.id.txtRole);
        scrollView = (ObservableScrollView) mView.findViewById(R.id.scrollView);

        rlCustomer = (RelativeLayout) mView.findViewById(R.id.rlCustomer);
        rlPartner = (RelativeLayout) mView.findViewById(R.id.rlPartner);
        meAccount = (RelativeLayout) mView.findViewById(R.id.meAccount);


        tv_city = (TextView) mView.findViewById(R.id.txt_address);
        tv_qytime = (TextView) mView.findViewById(R.id.txtTime);
        tv_pf = (TextView) mView.findViewById(R.id.txtpf);
        panelDetail = mView.findViewById(R.id.panelDetail);

        messageQbv = new QBadgeView(context);
        messageQbv.bindTarget(mView.findViewById(R.id.F_right)).setBadgeGravity(Gravity.TOP | Gravity.END);
        messageQbv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                presenter.goMessagePage(context);
            }
        });

        mView.findViewById(R.id.txtLogin).setOnClickListener(this);
        mView.findViewById(R.id.txtRegister).setOnClickListener(this);
        mView.findViewById(R.id.rlOrder).setOnClickListener(this);
//        mView.findViewById(R.id.F_right).setOnClickListener(this);
        mView.findViewById(R.id.decorateManager).setOnClickListener(this);
        mView.findViewById(R.id.scheme).setOnClickListener(this);
        mView.findViewById(R.id.rlFavorite).setOnClickListener(this);
        mView.findViewById(R.id.layout_contract).setOnClickListener(this);
        mView.findViewById(R.id.lineLay_login).setOnClickListener(this);

        rl_CSD = (RelativeLayout) mView.findViewById(R.id.rl_CSD);
        rl_CSD.setOnClickListener(this);
        rl_evaluate.setOnClickListener(this);
        rlCustomer.setOnClickListener(this);
        rl_lineSettings.setOnClickListener(this);
        rlPartner.setOnClickListener(this);
        meAccount.setOnClickListener(this);
        txtQR.setOnClickListener(this);

        gridView.setAdapter(presenter.initGridAdapter(context));
        gridView.setOnItemClickListener(this);

        scrollView.setOnScrollChangedListener(this);

        TextView title = (TextView) titleView.findViewById(R.id.title);
        title.setText("我的");
        titleMessageQbv = new QBadgeView(context);
        titleMessageQbv.bindTarget(mView.findViewById(R.id.flIcon1)).setBadgeGravity(Gravity.TOP | Gravity.END);
        titleMessageQbv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                presenter.goMessagePage(context);
            }
        });
        showRightButton(R.drawable.i_ring).setOnClickListener(this);

    }


    @Override
    protected void initData() {
        photoPopupwindow = new SelectPhotoPopupwindow(context, this);
    }

    @Override
    public void onResume() {
        super.onResume();
        String role = SPUtils.get(context,SPConfig.ROLE_ID,"").toString();
        if (presenter.network(context)){
            CheckUtil.getCurrentRoleId(context,false, new OnLoadListener() {
                @Override
                public void onLoad(Object content) {
                    presenter.onLoad(context);
                }
            });
            if (!TextUtils.isEmpty(role)){
                presenter.getSearchNoticeCountForCustomer(context, new OnLoadListener() {
                    @Override
                    public void onLoad(Object content) {
                        if (content != null && content instanceof Integer){
                            try {
                                int num = (int) content;
                                if (num > 0) {
                                    messageQbv.setBadgeText(String.valueOf(num))
                                            .setGravityOffset(2, 2, true)
                                            .setBadgeTextSize(8, true);

                                    titleMessageQbv.setBadgeText(String.valueOf(num))
                                            .setGravityOffset(2, 2, true)
                                            .setBadgeTextSize(8, true);
                                } else {
                                    messageQbv.setBadgeText(String.valueOf(num))
                                            .setGravityOffset(2, 2, true)
                                            .setBadgeTextSize(8, true)
                                            .hide(false);

                                    titleMessageQbv.setBadgeText(String.valueOf(num))
                                            .setGravityOffset(2, 2, true)
                                            .setBadgeTextSize(8, true)
                                            .hide(false);
                                }
                            }catch (Exception e){
                                messageQbv.setBadgeText(String.valueOf(0))
                                        .setGravityOffset(2, 2, true)
                                        .setBadgeTextSize(8, true)
                                        .hide(false);

                                titleMessageQbv.setBadgeText(String.valueOf(0))
                                        .setGravityOffset(2, 2, true)
                                        .setBadgeTextSize(8, true)
                                        .hide(false);
                            }
                        }else{
                            messageQbv.setBadgeText(String.valueOf(0))
                                    .setGravityOffset(2, 2, true)
                                    .setBadgeTextSize(8, true)
                                    .hide(false);

                            titleMessageQbv.setBadgeText(String.valueOf(0))
                                    .setGravityOffset(2, 2, true)
                                    .setBadgeTextSize(8, true)
                                    .hide(false);
                        }
                    }
                });
            }

        }


    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        presenter.onItemClick(context,1,orderTypes[position]);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            //消息
//            case R.id.F_right:
//            case R.id.flIcon1:
//                presenter.goMessagePage(context);
//                break;
            //账户
            case R.id.meAccount:
                if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)){
                    presenter.toMeAccount(context);

                }else {
                    LoginActivity.logout(context);
                }

                break;
            //合伙人
            case R.id.rlPartner:

                if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)){
                    presenter.toMePartner(context);

                }else {
                    context.startActivity(new Intent(context, LoginActivity.class));
                }


                break;
            //登陆
            case R.id.txtLogin:
                presenter.toLogin(context);
                break;
            //注册
            case R.id.txtRegister:
                presenter.goRegisterPage(context);
                break;
            //项目管理
            case R.id.decorateManager:
                if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)){
                    ((MainActivity)context).setFragmentIndex(1);
                }else {
                    LoginActivity.logout(context);
                }
                break;
            //客户
            case R.id.rlCustomer:
                if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)){
                    presenter.goCustomer(context);

                }else {
                    context.startActivity(new Intent(context, LoginActivity.class));
                }
                break;
            //方案
            case R.id.scheme:
               // startActivity(new Intent(context, ProgramPriceActivity.class));
                String role = SPUtils.get(context,SPConfig.ROLE_ID,"").toString();
                if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)){
                    if (role.contains("0")){
                        presenter.goSchemePage(context);
                    }else{
                        Utils.showToast(context,"您没有设计师权限，不能查看方案");
                    }
                }else {
                    LoginActivity.logout(context);
                }
                break;
            //订单
            case R.id.rlOrder:
                presenter.goAllOrderPage(context);
                break;
            //收藏
            case R.id.rlFavorite:
                if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)){
                    presenter.goFavoritePage(context);
                }else {
                    context.startActivity(new Intent(context, LoginActivity.class));
                }
                break;
            //合同
            case R.id.layout_contract:
                if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)){
                    presenter.goContractPage(context);
                }else {
                    LoginActivity.logout(context);
                }
                break;
            //评价
            case R.id.layout_evaluate:
                if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)){
                    presenter.goEvaluatePage(context);
                }else {
                    context.startActivity(new Intent(context, LoginActivity.class));
                }

                break;
            //设置
            case R.id.lineSettings:
                if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)){
                    presenter.goSettingsPage(context);
                }else {
                    LoginActivity.logout(context);
                }
                break;
            //客服与投诉
            case R.id.rl_CSD:
                if (!TextUtils.isEmpty(ConfigValue.DATA_KEY)){
                    presenter.goCSDPage(context);
                }else {
                    context.startActivity(new Intent(context, LoginActivity.class));
                }

                break;

            case R.id.txtQR:
                String qrCode = (String) SPUtils.get(context, SPConfig.QR_CODE,"");
                if (!TextUtils.isEmpty(qrCode)){
                    Intent intent=new Intent(context, ShareSqcodeActivity.class);
                    intent.putExtra("QRCODE",qrCode);
                    context.startActivity(intent);
                }
                break;

        }
    }

    @Override
    public MePresenter initPresenter() {
        return new MePresenter();
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void changeUIToLogout() {
        lineLay_not_login.setVisibility(View.VISIBLE);
        lineLay_login.setVisibility(View.GONE);
    }

    @Override
    public void reloadGridAdapter(QuickAdapter<MeIcon> adapter) {
        gridView.setAdapter(adapter);
    }

    @Override
    public void changeUIToLogin() {
        lineLay_not_login.setVisibility(View.GONE);
        ll_detail.setVisibility(View.VISIBLE);
        lineLay_login.setVisibility(View.VISIBLE);


        Picasso.with(context).load(FileUtils.rePath(ConfigValue.userInfo.getUrl())).networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE)
                .placeholder(R.drawable.i_head_default)
                .into(headPhoto);
        String nickName = SPUtils.get(context, SPConfig.USERNAME, "").toString();
        String roleId = SPUtils.get(context,SPConfig.ROLE_ID,"").toString();
        String roleName = "";


        if (!TextUtils.isEmpty(roleId)){
            for (int i = 0;i < 4;i++){
                if (roleId.contains(String.valueOf(i))){
                    switch (i){
                        case 0:
                            roleName += "设计师、";
                            break;
                        case 1:
                            roleName += "项目经理、";
                            break;
                        case 2:
                            roleName += "监理、";
                            break;
                        case 3:
                            roleName += "体验店、";
                            break;
                    }
                }
            }
            if (!TextUtils.isEmpty(roleName)){
                roleName = roleName.substring(0,roleName.lastIndexOf("、"));
            }
        }

        if (!TextUtils.isEmpty(nickName)){
            txtNickname.setText(nickName);
        }else{
            txtNickname.setText("");
        }

        if (!TextUtils.isEmpty(roleName)){
            txtRole.setText(roleName);
        }else{
            txtRole.setText("无角色");
        }

        String qrCode = (String) SPUtils.get(context, SPConfig.QR_CODE,"");
        if (TextUtils.isEmpty(qrCode)){
            txtQR.setVisibility(View.GONE);
        }else{
            txtQR.setVisibility(View.VISIBLE);
        }

        if (roleId != null && roleId.contains("0")){
            String sysPoint = SPUtils.get(context, SPConfig.SYS_SPOINTS, "").toString();
            if (!TextUtils.isEmpty(sysPoint)){
                tv_pf.setText(sysPoint);
            }else{
                tv_pf.setText("");
            }

            tv_pf.setVisibility(View.VISIBLE);
        }else{
            tv_pf.setVisibility(View.GONE);
        }

        if (ConfigValue.userInfo != null){
            panelDetail.setVisibility(View.VISIBLE);
            String city = ConfigValue.userInfo.getAddress();
            if (!TextUtils.isEmpty(city)){
                tv_city.setText(city.split(" ")[0]);
            }else{
                tv_city.setText("");
            }
            String qyTime = SPUtils.get(context, SPConfig.SIGN_TIME, "").toString();
            if (!TextUtils.isEmpty(qyTime)){
                tv_qytime.setText(qyTime);
            }else {
                tv_qytime.setText("");
            }
        }else {
            panelDetail.setVisibility(View.GONE);
        }

    }

    @Override
    public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
        if (checkIsVisible(context, mainTitle)) {
            mainTitle.setVisibility(View.VISIBLE);
            titleView.setVisibility(View.GONE);
        } else {
            mainTitle.setVisibility(View.GONE);
            titleView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        messageQbv.setBadgeText(String.valueOf(0))
                .setGravityOffset(2, 2, true)
                .setBadgeTextSize(8, true)
                .hide(false);

        titleMessageQbv.setBadgeText(String.valueOf(0))
                .setGravityOffset(2, 2, true)
                .setBadgeTextSize(8, true)
                .hide(false);
    }
}
